var cus_workbench = function() {
	//地图
	var map;
	var _cusId;
	return {
		/**
		 * 初始化页面元素
		 */
		init : function(cusId) {
			_cusId = cusId;
			//初始化客户下拉框
			//cus_workbench.initCustomerSelect();
			cusmonitorConsoleDetailCount = 0;
			//查询
			$("#btn_query").click(function() {
				getPackAlertInfoList();
			});
			
			    //根据所选择客户查询电池报警信息
				cus_workbench.handleCountInfoPanel();
				cus_workbench.handleLocationInfo();
				//$("#btn_query").click();
			
			$(function(){
				$('.cusInfoId').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('#btn_query').click();
					}
				});
				
				$("#alertName_select").change(function(){
				    $('#btn_query').click();
				})
				
				$("#alertLevel_select").change(function(){
					$('#btn_query').click();
				})
				
				//地图keyup事件
				$('#queryPackCode').bind('keyup',function(e){
					if(e.keyCode == '13'){
						cus_workbench.getLocationInfo();
					}
				})
			});
			
			//处理页面刷新
			var cycle = util.getRefreshCycle("REFRESH_CYCLE");
			//启用页面刷新
			cusmonitorConsoleRefreshTimer = window.setInterval(function(){
				App.blockUI($("#refreshZone"));//开始loading
				cus_workbench.handleCountInfoPanel();
				cus_workbench.getLocationInfo();
				//$("#btn_query").click();
			},cycle);
			
			function getPackAlertInfoList() {
				$("#alert_info_table_processing").removeClass("hide");
				var aoData = [];
				aoData.push({
					"name" : "alertName",
					"value" : $("#alertName_select").val()
				});
				aoData.push({
					"name" : "levelName",
					"value" : $("#alertLevel_select").val()
				});
				aoData.push({
					"name" : "alertTime",
					"value" : $("#datepicker").val()
				});
				aoData.push({
					"name" : "alertInfo",
					"value" : $("#cusInfoId").val()
				});
				aoData.push({
					"name" : "cusId",
					"value" : _cusId
				});
				$.ajax({
					"type" : "post",
					"url" : "monitor/workbench/getPackAlertInfoList.mvc",
					"async" : true,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						$("#alert_info_table tbody").html("");
						packAlertInfoList = resp.aaData;
						$(".alert-content-list").scrollTop(0);
						nextPage = 2;
						if (packAlertInfoList.length == 0) {
							$("#alert_info_table tbody").append('<tr><td colspan="7" class="dataTables_empty">没有数据</td></tr>');
						} else {
							totalPage = Math.ceil(packAlertInfoList.length/pageSize);
							loadPackAlertInfo(1);
						}
						$("#alert_info_table_processing").addClass("hide");
					}
				});
			}
			
			$(".alert-content-list").on('scroll',function () {
				var winHeight = $(".alert-content-list").height();
		    	var scrollTop = $(".alert-content-list").scrollTop();
		    	var scrollHeight = $(".alert-content-list")[0].scrollHeight;
		    	if (scrollHeight - (scrollTop + winHeight) < 100 && nextPage <= totalPage) {
		    		loadPackAlertInfo(nextPage++);
		    	}
	        });
			
			function loadPackAlertInfo(page) {
				var startRec = pageSize * (page - 1);
				var endRec = (pageSize * page) > packAlertInfoList.length ? packAlertInfoList.length : (pageSize * page);
				
				var html = "";
				for (; startRec < endRec; startRec++) {
					var packAlertInfo = packAlertInfoList[startRec]
					var category = "bg-orangedeep";
					if (packAlertInfo.category == '1') {
						category = "bg-orange";
					}
					html += '<tr>' +
								'<td><div><span class="' + category + '"></span></div></td>' +
								'<td><div>' + packAlertInfo.packCode + '</div></td>' +
								'<td><div>' + packAlertInfo.clientId + '</div></td>' +
								'<td><div>' + packAlertInfo.customer + '</div></td>' +
								'<td><div>' + packAlertInfo.alertName + '</div></td>' +
								'<td><div>&nbsp;' + packAlertInfo.levelName + '</div></td>' +
								'<td><div>' + packAlertInfo.alertTime + '</div></td>' +
						    '</tr>';
				}
				$("#alert_info_table tbody").append(html);
			}
			
		},
		
		/**
		 * 根据选择客户加载统计信息
		 */
		handleCountInfoPanel:function(){
			//选了客户
			if(_cusId){
				$.ajax({
					'type':'post',
					'url':'monitor/workbench/getCustomPackAlertInfo.mvc',
					'dataType':'json',
					'async':true,
					'data':{'cusId':_cusId},
					'success':function(data){
						$("#totalNum").empty().append(data.total);
						if(data.todayAlertNum >99){
							$("#alertNum").empty().append("99+");
						} else {
							$("#alertNum").empty().append(data.todayAlertNum);
						}
						$("#chargingNum").empty().append(data.charging);
						$("#unChargingNum").empty().append(data.unCharging);
						$("#powerFail").empty().append(data.powerFail);
						
						if(data.barChartData.length>0){
							$(".chart_div").show();
							cus_workbench.setBarChart(data.barChartData);
						    cus_workbench.setPieChart(data.pieChartData);
						} else {
							$(".chart_div").hide();
						}
						
					},
					'error':function(msg){
						console.log("error");
					}
				})
			}else {
				//未选择客户
				$("#totalNum").empty();
				$("#alertNum").empty();
				$("#chargingNum").empty();
				$("#unChargingNum").empty();
			}
		},
		
		/**
		 * 处理电池位置信息
		 */
		handleLocationInfo:function(){
			if(_cusId){
				map = new BMap.Map("mapZoneDiv");
				map.centerAndZoom(new BMap.Point(116.417854,39.921988),6);//默认中心点
				map.enableScrollWheelZoom(true);//缩放
                //向地图中添加缩略图控件  
                var ctrlOve = new window.BMap.OverviewMapControl({  
                    anchor: BMAP_ANCHOR_BOTTOM_RIGHT,  
                    isOpen: 1  
                });  
                map.addControl(ctrlOve);
                //向地图中添加比例尺控件  
                var ctrlSca = new window.BMap.ScaleControl({  
                    anchor: BMAP_ANCHOR_BOTTOM_LEFT  
                });  
                map.addControl(ctrlSca); 
                
                //添加地图自定义控件
                function queryPackCode(){
              	  this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
                    this.defaultOffset = new BMap.Size(10, 10); // 距离左上角位置
                    this.searchBox = document.createElement("input");// 搜索框
                    this.searchBox.setAttribute("type", "text"); 
                    this.searchBox.setAttribute("placeHolder","请输入电池ID");
                }
                queryPackCode.prototype = new BMap.Control();
                queryPackCode.prototype.initialize = function(map){
                  // 创建一个DOM元素
                  var div = document.createElement("div");
                  var txt = this.searchBox;
                  txt.className = "form-control";
                  txt.setAttribute("id", "queryPackCode");
                  div.appendChild(txt);
                  // 添加DOM元素到地图中
                  map.getContainer().appendChild(div);
                  // 将DOM元素返回
                  return div;
                }
                // 创建控件
                var queryPackCodeCtrl = new queryPackCode();
                // 添加到地图当中
                map.addControl(queryPackCodeCtrl);
                
                cus_workbench.getLocationInfo()
			}
		},
		
		
		/**
		 *  根据选中的电池id去获取位置信息 并在地图中绘制  
		 * @param packIdsArray 选中的电池id数组
		 */
		getLocationInfo:function(packIdsArray){
			map.centerAndZoom(new BMap.Point(116.417854,39.921988),6);//默认中心点
			$.ajax({
				'type':'post',
				'url':'monitor/workbench/getPackLocationInfo.mvc',
				'dataType':'json',
				'async':false,
				'data':{'packCodes':$("#queryPackCode").val(), 'cusId':_cusId},
				'success':function(data){
					//清空上次标注
					map.clearOverlays();
					if(data.length>0){
						var points = new Array();
						var markers = new Array();
						for ( var int = 0; int < data.length; int++) {
							var new_point = new BMap.Point(data[int].longitude, data[int].latitude);
							new_point.info = data[int];
							points.push(new_point);
							markers.push(new BMap.Marker(new_point));
						}
						var markerClusterer = new BMapLib.MarkerClusterer(map, {markers:markers}); 
						markerClusterer.setMaxZoom(13);
						markerClusterer.setGridSize(100);
						var options = {
				                size: BMAP_POINT_SIZE_SMALL,
				                shape: BMAP_POINT_SHAPE_WATERDROP
				            }
				            var pointCollection = new BMap.PointCollection(points, options);  // 初始化PointCollection
				            pointCollection.addEventListener('click', function (e) {
				    			var point = new BMap.Point(e.point.lng, e.point.lat); 
				    			var _facName = e.point.info.facName;
								_facName = e.point.info.facName == null?'未关联厂区':e.point.info.facName;
				    			var lableInfo ="<table><tr><td><b>最后采集时间：</b>"+e.point.info.gatherTime+"</td><td><b>采集终端ID：</b>"+e.point.info.clientId+"</td></tr>" +
								"<tr><td><b>电池ID：</b>"+e.point.info.packCode+"</td><td><b>SOC：</b>" + e.point.info.soc + "</td></tr>" +
								"<tr><td><b>总电压：</b>" + e.point.info.vol + "V</td><td><b>总电流：</b>" + e.point.info.current +"A</td></tr>" +
								"<tr><td><b>客户：</b>" + e.point.info.cusName + "</td><td><b>所属厂区：</b>" + _facName + "</td></tr>" +
								"<tr><td><b>地理位置：</b>"+cus_workbench.decodeAddress(e.point.lng, e.point.lat)+"</td><td></td></tr>" +
								"<tr><td></td><td><a style=\"cursor:pointer;\" onclick=\"workbench.showDetail('"+e.point.info.packCode+"','" + e.point.info.clientId + "')\">查看详情</a></td></tr>" +
									"</table>";
				    			
				    			var infowindow = new BMap.InfoWindow(lableInfo);
				    			map.openInfoWindow(infowindow, point);
				            });
				        map.addOverlay(pointCollection);  // 添加Overlay
					}
					App.unblockUI($("#refreshZone"));//停止loading
					
				},
				'error':function(msg){
					App.unblockUI($("#refreshZone"));//停止loading
					console.log("error");
				}
			})
		},
		/**
		 * 根据经纬度解析地理位置
		 * @param lng 经度
		 * @param lat 维度
		 */
		decodeAddress:function(lng, lat){
			var address = "";
			$.ajax({
				type:'post',
				url:'monitor/workbench/decodeAddress.mvc',
				async:false,
				data:{'lng':lng,'lat':lat},
				dataType:'json',
				success:function(data){
					address = data.address;
				}
			})
			return address;
		},
		
		/**
		 *  跳转道监控详情页面
		 * @param p 电池id
		 * @param c 终端id
		 */
		showDetail:function(p, c){
			util.showContent("pages/monitor/packDataMonitor_detail.jsp",{'clientId':c,'packCode':p});
		},
				/**
		 * 设置柱形图
		 * @param data 数据
		 */
		setBarChart:function(data){
			var dataX = new Array();
			var dataY = new Array();
			for (var index = 0; index < data.length; index++) {
				dataX.push(data[index]['x']);
				dataY.push(data[index]['y']);
			}
			option = {
					    tooltip: {
					        trigger: 'axis'	
					    },
					    legend: {
					        data:['报警数']
					    },
					    toolbox: {
					        show: false
					    },
					    xAxis:  {
					        type: 'category',
					        splitLine:{show:true},
					        data: dataX
					    },
					    yAxis: {
					        type: 'value',
					        splitLine:{show:true},
					        axisLabel: {
					            formatter: '{value}'
					        }
					    },
					    series: [{
					    	    name:'报警数',
					            type:'bar',
					            data:dataY,
					            barWidth: '40%',
					            itemStyle: {
					            	normal: {
							            label : {
			                                  show: true,
			                                  position: 'top'
			                              }
					            	}
			            		}
					        }]
					};
			    var myChart = echarts.init(document.getElementById("alert_bar_chart"),'macarons');
			    myChart.setOption(option,true);
		},
		
		/**
		 * 设置饼状图
		 * @param data 数据
		 */
		setPieChart:function(data){
			var dataX = new Array();
			var dataY = new Array();
			for (var index = 0; index < data.length; index++) {
				dataX.push(data[index]['x']);
				dataY.push({value:data[index]['y'],name:data[index]['x']});
			}
			option = {
			    tooltip : {
			        trigger: 'item',
			        formatter: "{a} <br/>{b} : {c} ({d}%)"
			    },
			    legend: {
			        left: 'center',
			        data: dataX
			    },
			    series : [
			        {
			        	name: '告警级别',
			            type: 'pie',
			            radius : '55%',
			            center: ['50%', '60%'],
			            data: dataY,
			        itemStyle:{ 
			            normal:{ 
			                  label:{ 
			                    show: true, 
			                    formatter: '{b} : {c} ({d}%)' 
			                  }, 
			                  labelLine :{show:true} 
			                } 
			            } 
			        }
			    ]
			};
			var myChart = echarts.init(document.getElementById("alert_pie_chart"),'macarons');
			myChart.setOption(option,true);
		},
		
				/**
		 * 初始化客户选择下拉框
		 * @returns
		 */
		initCustomerSelect:function() {
			$.ajax({  
		           type: 'POST',  
		           url: "monitor/workbench/getAlertTableQuerySelectOption.mvc", //url    
		           dataType: "json",
		           async:false,
		           ContentType: "application/json; charset=utf-8",  
		           success: function (data) {
			           util.createOption("alertName_select", "全部", data.alertNameList);
			           util.createOption("alertLevel_select", "全部", data.alertLevelList);
		           },  
		           error: function (msg) {  
		           	console.log(123123);
		           }  
			});
		}
		
	};
}();
